<template>
  <div class="ai-chat-container">
    <!-- 侧边栏 -->
    <div class="sidebar">
      <!-- 新建对话按钮 -->
      <button class="new-chat-btn" @click="createNewChat">
        <i class="fa fa-plus"></i>
        <span>新建对话</span>
      </button>
      
      <!-- 历史对话列表 -->
      <div class="history-list">
        <!-- 今天的对话 -->
        <div v-if="groupedHistory.today.length > 0" class="history-group">
          <div class="group-title">今天</div>
          <div v-for="chat in groupedHistory.today" 
               :key="chat.id" 
               :class="['history-item', { active: currentChatId === chat.id }]"
               @click="switchChat(chat.id)">
            <i class="fa fa-comment"></i>
            <span class="title">{{ chat.title }}</span>
            <i class="fa fa-trash delete-icon" @click.stop="deleteChat(chat.id)"></i>
          </div>
        </div>

        <!-- 最近7天的对话 -->
        <div v-if="groupedHistory.lastWeek.length > 0" class="history-group">
          <div class="group-title">最近7天</div>
          <div v-for="chat in groupedHistory.lastWeek" 
               :key="chat.id" 
               :class="['history-item', { active: currentChatId === chat.id }]"
               @click="switchChat(chat.id)">
            <i class="fa fa-comment"></i>
            <span class="title">{{ chat.title }}</span>
            <i class="fa fa-trash delete-icon" @click.stop="deleteChat(chat.id)"></i>
          </div>
        </div>

        <!-- 更早的对话 -->
        <div v-if="groupedHistory.older.length > 0" class="history-group">
          <div class="group-title">更早</div>
          <div v-for="chat in groupedHistory.older" 
               :key="chat.id" 
               :class="['history-item', { active: currentChatId === chat.id }]"
               @click="switchChat(chat.id)">
            <i class="fa fa-comment"></i>
            <span class="title">{{ chat.title }}</span>
            <i class="fa fa-trash delete-icon" @click.stop="deleteChat(chat.id)"></i>
          </div>
        </div>
      </div>
    </div>

    <!-- 主聊天区域 -->
    <div class="main-content">
      <!-- 顶部工具栏 -->
      <div class="toolbar">
        <el-select v-model="selectedModel" placeholder="选择模型" class="model-select">
          <el-option label="GPT-3.5" value="gpt-3.5" />
          <el-option label="GPT-4" value="gpt-4" />
          <el-option label="Claude" value="claude" />
        </el-select>
      </div>

      <!-- 聊天记录区域 -->
      <div class="chat-history" ref="chatHistory">
        <div v-for="(message, index) in currentChat.messages" 
             :key="index" 
             :class="['message', message.role]">
          <div class="avatar">
            <el-avatar :size="36" :src="message.role === 'assistant' ? '/ai-avatar.png' : '/user-avatar.png'" />
          </div>
          <div class="message-content">
            {{ message.content }}
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="input-wrapper">
        <div class="input-area">
          <textarea
            v-model="userInput"
            class="input-textarea"
            placeholder="发送消息..."
            @keydown.enter.exact.prevent="sendMessage"
            @keydown.enter.shift.prevent="handleShiftEnter"
            rows="1"
          ></textarea>
          <div class="action-buttons">
            <button class="action-btn">
              <i class="fa fa-paperclip"></i>
            </button>
            <button class="action-btn">
              <i class="fa fa-image"></i>
            </button>
            <button class="action-btn">
              <i class="fa fa-link"></i>
            </button>
            <button 
              class="send-btn" 
              @click="sendMessage"
              :disabled="isLoading"
            >
              <i v-if="!userInput.trim()" class="fas fa-microphone"></i>
              <i v-else class="fa fa-paper-plane"></i>
            </button>
          </div>
        </div>
        <div class="input-footer">
          <span class="hint">按 Enter 发送，Shift + Enter 换行</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { Plus, ChatDotRound, Delete, ArrowUp, Paperclip, Picture, Link, Microphone } from '@element-plus/icons-vue'

export default {
  name: 'AiChat',
  components: {
    Plus,
    ChatDotRound,
    Delete,
    ArrowUp,
    Paperclip,
    Picture,
    Link,
    Microphone
  },
  data() {
    return {
      chatHistory: this.generateMockData(),
      currentChatId: null,
      selectedModel: 'gpt-3.5',
      userInput: '',
      isLoading: false,
      currentChat: {
        messages: []
      }
    }
  },
  computed: {
    groupedHistory() {
      const now = new Date()
      const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
      const weekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000)

      return {
        today: this.chatHistory.filter(chat => new Date(chat.createTime) >= today),
        lastWeek: this.chatHistory.filter(chat => {
          const chatDate = new Date(chat.createTime)
          return chatDate >= weekAgo && chatDate < today
        }),
        older: this.chatHistory.filter(chat => new Date(chat.createTime) < weekAgo)
      }
    }
  },
  created() {
    // 初始化一个新对话
    this.createNewChat()
  },
  methods: {
    generateMockData() {
      const mockData = [
        {
          id: Date.now(),
          title: '新对话',
          createTime: new Date(),
          messages: []
        },
        {
          id: Date.now() - 1,
          title: '如何学习前端开发',
          createTime: new Date(),
          messages: [
            { role: 'user', content: '如何学习前端开发？' },
            { role: 'assistant', content: '前端开发学习路线包括HTML、CSS、JavaScript等...' }
          ]
        },
        {
          id: Date.now() - 2,
          title: 'Vue.js组件通信方式',
          createTime: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000),
          messages: [
            { role: 'user', content: 'Vue组件之间如何通信？' },
            { role: 'assistant', content: 'Vue组件通信有多种方式：props、emit、vuex等...' }
          ]
        },
        {
          id: Date.now() - 3,
          title: 'React Hooks使用',
          createTime: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000),
          messages: [
            { role: 'user', content: '请介绍React Hooks的使用' },
            { role: 'assistant', content: 'React Hooks是React 16.8引入的新特性...' }
          ]
        },
        {
          id: Date.now() - 4,
          title: '后端架构设计',
          createTime: new Date(Date.now() - 10 * 24 * 60 * 60 * 1000),
          messages: [
            { role: 'user', content: '如何设计可扩展的后端架构？' },
            { role: 'assistant', content: '后端架构设计需要考虑多个方面：可扩展性、可维护性...' }
          ]
        }
      ]
      return mockData
    },
    createNewChat() {
      const newChat = {
        id: Date.now(),
        title: '新对话',
        createTime: new Date(),
        messages: []
      }
      this.chatHistory.unshift(newChat)
      this.currentChatId = newChat.id
      this.currentChat = newChat
    },
    switchChat(chatId) {
      this.currentChatId = chatId
      this.currentChat = this.chatHistory.find(chat => chat.id === chatId)
    },
    deleteChat(chatId) {
      const index = this.chatHistory.findIndex(chat => chat.id === chatId)
      this.chatHistory.splice(index, 1)
      if (this.currentChatId === chatId) {
        if (this.chatHistory.length > 0) {
          this.switchChat(this.chatHistory[0].id)
        } else {
          this.createNewChat()
        }
      }
    },
    async sendMessage() {
      if (!this.userInput.trim()) return
      
      this.isLoading = true
      
      // 添加用户消息
      this.currentChat.messages.push({
        role: 'user',
        content: this.userInput
      })

      // 更新对话标题（使用用户的第一条消息）
      if (this.currentChat.messages.length === 1) {
        this.currentChat.title = this.userInput.slice(0, 20) + (this.userInput.length > 20 ? '...' : '')
      }

      try {
        // 模拟AI响应
        await new Promise(resolve => setTimeout(resolve, 1000))
        this.currentChat.messages.push({
          role: 'assistant',
          content: `使用${this.selectedModel}的回复消息`
        })
      } finally {
        this.isLoading = false
        this.userInput = ''
        this.$nextTick(() => {
          this.scrollToBottom()
        })
      }
    },
    scrollToBottom() {
      const chatHistory = this.$refs.chatHistory
      chatHistory.scrollTop = chatHistory.scrollHeight
    },
    handleShiftEnter(e) {
      // 处理 Shift + Enter 换行
      this.userInput += '\n'
    }
  }
}
</script>

<style scoped>
.ai-chat-container {
  height: 100vh;
  display: flex;
  background: #ffffff;
}

.sidebar {
  width: 260px;
  background: #f7f7f8;
  padding: 8px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.new-chat-btn {
  width: 100%;
  border: 1px solid #e5e5e5;
  background: #ffffff;
  color: #333;
  border-radius: 6px;
  padding: 12px;
  display: flex;
  align-items: center;
  gap: 12px;
  transition: all 0.3s;
}

.new-chat-btn:hover {
  background: #f0f0f0;
}

.history-list {
  flex: 1;
  overflow-y: auto;
  margin-top: 8px;
}

.history-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border-radius: 6px;
  cursor: pointer;
  gap: 12px;
  color: #333;
  transition: all 0.3s;
}

.history-item:hover {
  background: #ececec;
}

.history-item.active {
  background: #e5e5e5;
}

.history-item .title {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 14px;
}

.delete-icon {
  opacity: 0;
  transition: opacity 0.2s;
  color: #666;
  cursor: pointer;
}

.history-item:hover .delete-icon {
  opacity: 1;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #ffffff;
}

.toolbar {
  padding: 8px 16px;
  border-bottom: 1px solid #e5e5e5;
  background: #ffffff;
}

.model-select {
  width: 200px;
}

.chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 0;
  margin: 0;
}

.message {
  display: flex;
  gap: 24px;
  padding: 24px;
  margin: 0 24px;
  max-width: none;
  background: #ffffff;
}

.message.user {
  flex-direction: row-reverse;
  gap: 16px;
}

.message.assistant {
  background: #ffffff;
}

.avatar {
  flex-shrink: 0;
  width: 36px;
  margin-top: 8px;
}

.message-content {
  flex: 1;
  padding: 12px 16px;
  background: #ffffff;
  border: 1px solid #e5e5e5;
  border-radius: 8px;
  color: #333;
  font-size: 15px;
  line-height: 1.6;
  max-width: 80%;
  box-shadow: 0 1px 2px rgba(0,0,0,0.05);
}

.message.user .message-content {
  text-align: left;
  border-color: #409EFF;
  background: #ecf5ff;
  color: #333;
}

.message {
  border-bottom: none;
}

.input-wrapper {
  padding: 16px 24px 24px;
  background: #ffffff;
  border-top: 1px solid #e5e5e5;
}

.input-area {
  position: relative;
  max-width: 768px;
  margin: 0 auto;
  background: #ffffff;
  border: 1px solid #e5e5e5;
  border-radius: 12px;
  padding: 8px;
  box-shadow: 0 0 8px rgba(0,0,0,0.1);
}

.input-area:focus-within {
  border-color: #409EFF;
}

.input-textarea {
  width: 100%;
  min-height: 24px;
  max-height: 200px;
  padding: 8px;
  border: none;
  outline: none;
  resize: none;
  font-size: 15px;
  line-height: 1.5;
  color: #333;
  background: transparent;
  font-family: inherit;
}

.input-textarea::placeholder {
  color: #999;
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 0 8px;
  margin-top: 4px;
}

.action-btn {
  width: 32px;
  height: 32px;
  padding: 6px;
  color: #666;
  background: transparent;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-btn:hover {
  background: #f5f5f5;
  color: #409EFF;
}

.send-btn {
  margin-left: auto;
  width: 32px;
  height: 32px;
  padding: 6px;
  background: #19c37d;
  color: white;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.send-btn:hover {
  background: #1a8f5f;
}

.send-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.icon {
  width: 100%;
  height: 100%;
  fill: currentColor;
}

.input-footer {
  text-align: center;
  margin-top: 8px;
}

.hint {
  color: #999;
  font-size: 12px;
}

/* 自定义滚动条样式 */
.chat-history::-webkit-scrollbar,
.history-list::-webkit-scrollbar {
  width: 6px;
}

.chat-history::-webkit-scrollbar-thumb,
.history-list::-webkit-scrollbar-thumb {
  background: #cccccc;
  border-radius: 3px;
}

.chat-history::-webkit-scrollbar-track,
.history-list::-webkit-scrollbar-track {
  background: transparent;
}

.history-group {
  margin-bottom: 20px;
}

.group-title {
  padding: 8px 12px;
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

.history-item {
  margin-bottom: 4px;
}

/* 调整图标样式 */
.action-btn i {
  font-size: 16px;
}

.send-btn i {
  font-size: 16px;
}

.new-chat-btn i {
  font-size: 14px;
}

.history-item i {
  font-size: 14px;
}

.delete-icon {
  opacity: 0;
  transition: opacity 0.2s;
  color: #666;
  cursor: pointer;
}

/* 其他样式保持不变 */
</style>
